package lgz

import (
	"errors"
	"fmt"
	"strings"
)

type Lgz struct {
	Config
}

type Config struct {
	AccessKey    string
	AssessSecret string
}

func (this *Lgz) New(config *Config) {
	this.AccessKey = config.AccessKey
	this.AssessSecret = config.AssessSecret
}

func (this *Lgz) GetAccessToken() (string, error) {
	params := map[string]interface{}{
		"accessKey":    this.AccessKey,
		"accessSecret": this.AssessSecret,
	}
	result, err := httpPost(
		DOMAIN+API_GET_ACCESS_TOKEN,
		params,
	)
	if err != nil {
		return "", err
	}

	if result["errcode"] != LGZ_OK {
		err := errors.New("获取access_token出错：" + result["errmsg"].(string))
		return "", err
	}
	return result["accessToken"].(string), nil
}

func (this *Lgz) GetDeviceOnlineList(
	accessToken string,
) (
	[]string,
	error,
) {
	params := map[string]interface{}{
		"accessToken": accessToken,
	}
	result, err := httpPost(
		DOMAIN+DEVICE_ONLINE_LIST,
		params,
	)
	if err != nil {
		return []string{}, err
	}
	if result["errcode"] != LGZ_OK {
		err := errors.New("获取乐关注在线设备出错" + result["errmsg"].(string))
		return []string{}, err
	}

	str := fmt.Sprint(result["devices"])
	str = str[1 : len(str)-1]
	devices := strings.Split(str, " ")

	return devices, nil
}

func (this *Lgz) GetUserQrcode(
	accessToken string,
	userID string,
) (
	string,
	error,
) {
	params := map[string]interface{}{
		"accessToken": accessToken,
		"userID":      userID,
	}
	result, err := httpPost(
		DOMAIN+USER_QRCODE,
		params,
	)
	if err != nil {
		return "", err
	}
	if result["errcode"] != LGZ_OK {
		err := errors.New("获取乐关注在线设备出错" + result["errmsg"].(string))
		return "", err
	}
	return result["qrcode"].(string), nil
}
